package com.dgut.legalservice.controller;

import com.dgut.legalservice.domain.Approval;
import com.dgut.legalservice.domain.Order;
import com.dgut.legalservice.domain.Product;
import com.dgut.legalservice.domain.User;
import com.dgut.legalservice.domain.attachment.Attachment;
import com.dgut.legalservice.domain.contract.*;
import com.dgut.legalservice.service.*;
import com.dgut.legalservice.tool.FileTool;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/contract")
public class ContractController {
    @Autowired
    IContractService contractService;

    @Autowired
    IAttachmentService attachmentService;

    @Autowired
    ProductService productService;

    @Autowired
    OrderService orderService;

    @Autowired
    UserService userService;

    @Autowired
    ApprovalService approvalService;

    //////////////后台管理部分

    //后台界面
    @RequestMapping("")
    public ModelAndView admin() {
        return new ModelAndView("/platform/header");
    }

    //定制模板管理页
    @RequestMapping("/customContractList")
    public ModelAndView findAllCustomContract(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
//        ModelAndView mv = new ModelAndView("/contract/customContract");
        ModelAndView mv = new ModelAndView("/platform/contract-template");
        List<Contract> contracts = contractService.findCustomContracts(pageNum, pageSize);
        PageInfo<Contract> page = new PageInfo<Contract>(contracts);
        mv.addObject("page", page);
        return mv;
    }

    //下载模板管理页
    @RequestMapping("/downloadContractList")
    public ModelAndView findAllDownloadContract(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
//        ModelAndView mv = new ModelAndView("/contract/downloadContract");
        ModelAndView mv = new ModelAndView("/platform/d-contract-template");
        List<Contract> contracts = contractService.findDownloadContracts(pageNum, pageSize);
        PageInfo<Contract> page = new PageInfo<Contract>(contracts);
        mv.addObject("page", page);
        return mv;
    }

    @RequestMapping("/showContract")
    @ResponseBody
    public Map<String, Object> findOneCustomContract(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        Contract contract = contractService.findContractById(id);
        map.put("contract", contract);
//        map.put("createBy", userService.findById(contract.getCreateBy()));
//        map.put("updateBy", userService.findById(contract.getUpdateBy()));
        return map;
    }

    @RequestMapping(value = "/addCustomContract", method = RequestMethod.POST)
    public ModelAndView addCustomContract(Contract contract, HttpServletRequest request) {
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        contract.setCreateBy(userId);
        contract.setUpdateBy(userId);
        contract.getContractSteps().get(0).setCreateBy(userId);
        contract.getContractSteps().get(0).setUpdateBy(userId);
        if (contract.getContractSteps() != null) {
            for (ContractStep contractStep : contract.getContractSteps()) {
                contractStep.setCreateBy(userId);
                contractStep.setUpdateBy(userId);
                if (contractStep.getContractItems() != null) {
                    for (ContractItem contractItem : contractStep.getContractItems()) {
                        contractItem.setCreateBy(userId);
                        contractItem.setUpdateBy(userId);
                    }
                }
            }
        }
        contractService.addCustomContract(contract);
        ModelAndView mv = new ModelAndView("redirect:/contract/customContractList");
        return mv;
    }

    @RequestMapping(value = "/addDownloadContract", method = RequestMethod.POST)
    public ModelAndView addDownloadContract(Contract contract, @RequestParam(name = "uploadFile") MultipartFile uploadFile, HttpServletRequest request) throws IOException {
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        Map<String, String> map = FileTool.fileUpload(uploadFile, request);
        if (map != null) {
            Attachment attachment = new Attachment(map.get("name"), map.get("path"), null, userId, userId);
            attachmentService.addAttachment(attachment);
            contract.setAtt(attachment);
        }
        contract.setCreateBy(userId);
        contract.setUpdateBy(userId);
        contractService.addDownloadContract(contract);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("redirect:/contract/downloadContractList");
        return mv;
    }

    @RequestMapping("/searchCustomContract")
    public ModelAndView searchCustomContract(ContractVo vo, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
        ModelAndView mv = new ModelAndView("/platform/contract-template");
        List<Contract> contracts = contractService.findCustomContractByVo(vo, pageNum, pageSize);
        PageInfo<Contract> page = new PageInfo<Contract>(contracts);
        mv.addObject("page", page);
        return mv;
    }

    @RequestMapping("/searchDownloadContract")
    public ModelAndView searchDownloadContract(ContractVo vo, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
        ModelAndView mv = new ModelAndView("/platform/d-contract-template");
        List<Contract> contracts = contractService.findDownloadContractByVo(vo, pageNum, pageSize);
        PageInfo<Contract> page = new PageInfo<Contract>(contracts);
        mv.addObject("page", page);
        return mv;
    }

    @RequestMapping("/editCustomContract")
    @ResponseBody
    public Contract editCustomContract(Integer id) {
//        ModelAndView mv = new ModelAndView();
//        mv.addObject("contract", contractService.findContractById(id));
//        mv.setViewName("/contract/editCustomContract");
        return contractService.findContractById(id);
    }

    @RequestMapping("/editDownloadContract")
    @ResponseBody
    public Contract editDownloadableContract(Integer id) {
//        ModelAndView mv = new ModelAndView();
//        mv.addObject("contract", contractService.findContractById(id));
//        mv.setViewName("/contract/editDownloadContract");
        return contractService.findContractById(id);
    }

    @RequestMapping("/deleteCustomContract")
    public ModelAndView deleteCustomContract(Integer id, String path) {
        contractService.deleteCustomContract(id);
        return new ModelAndView("redirect:" + path);
    }

    @RequestMapping("/deleteDownloadContract")
    public ModelAndView deleteDownloadContract(Integer contractId, Integer attId, String path) {
        contractService.deleteDownloadContract(contractId);
        attachmentService.deleteAttachment(attId);
        return new ModelAndView("redirect:" + path);
    }

    @RequestMapping("/updateCustomContract")
    public ModelAndView updateCustomContract(Contract contract, HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        contract.setUpdateBy(userId);
        contract.getContractSteps().get(0).setUpdateBy(userId);
        if (contract.getContractSteps() != null) {
            for (ContractStep contractStep : contract.getContractSteps()) {
                contractStep.setUpdateBy(userId);
                if (contractStep.getContractItems() != null) {
                    for (ContractItem contractItem : contractStep.getContractItems()) {
                        contractItem.setUpdateBy(userId);
                    }
                }
            }
        }
        contractService.updateCustomContract(contract);
        mv.setViewName("redirect:/contract/customContractList");
        return mv;
    }

    @RequestMapping("/updateDownloadContract")
    public ModelAndView updateDownloadContract(Contract contract, @RequestParam(name = "uploadFile") MultipartFile uploadFile, HttpServletRequest request) throws IOException {
        Integer userId = (Integer) request.getSession().getAttribute("userId");
        if (uploadFile != null && !uploadFile.isEmpty()) {
            //上传合同附件
            Map<String, String> map = FileTool.fileUpload(uploadFile, request);
            Attachment attachment = contract.getAtt();
            attachment.setName(map.get("name"));
            attachment.setPath(map.get("path"));
            attachment.setUpdateBy(userId);
            attachmentService.updateAttachment(attachment);
        }
        contract.setUpdateBy(userId);
        contractService.updateDownloadContract(contract);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("redirect:/contract/downloadContractList");
        return mv;
    }

    @RequestMapping("/findContractAudit")
    @ResponseBody
    public ContractAudit findContractAudit(Integer id) {
        return contractService.findContractAuditByOrderId(id);
    }

    //生成审批表
    @RequestMapping("/addContractApproval")
    public ModelAndView addContractApproval(Approval approval, Integer orderId) {
        approvalService.setFirStatus(approval, orderId);
        return new ModelAndView("redirect:/order/all");
    }

    @RequestMapping("/findAuditApproval")
    @ResponseBody
    public Map<String,Object> findAuditApproval(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("audit", contractService.findContractAuditByOrderId(id));
        map.put("approval", approvalService.selectById(id));
        return map;
    }

    @RequestMapping("/switchShareStatus")
    public ModelAndView switchShareStatus(Integer id, String path) {
        contractService.switchShareStatus(id);
        return new ModelAndView("redirect:" + path);
    }

    @RequestMapping("/download")
    public void download(Integer id, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Attachment attachment = attachmentService.findById(id);
        FileTool.downloadAttachment(attachment.getPath(), attachment.getName(), request, response);
    }

//////////////产品服务部分

    @RequestMapping("/test")
    public ModelAndView test() {
        ModelAndView mv = new ModelAndView("/contract/test");
        return mv;
    }

    //定制列表页
    @RequestMapping("/customServiceList")
    public ModelAndView customServiceList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "6") Integer pageSize) {
        ModelAndView mv = new ModelAndView("/contract/custom-service-list");
        List<Contract> contracts = contractService.findCustomContracts(pageNum, pageSize);
        PageInfo<Contract> page = new PageInfo<Contract>(contracts);
        mv.addObject("page", page);
        return mv;
    }

    //定制内容页
    @RequestMapping("/customServiceDetail")
    public ModelAndView customServiceDetail(Integer id) {
        ModelAndView mv = new ModelAndView("/contract/custom-service-detail");
        Contract contract = contractService.findContractById(id);
        mv.addObject("contract", contract);
        return mv;
    }

    //定制预览页
    @RequestMapping("/customServicePreview")
    public ModelAndView customServicePreview(Contract contract) {
        ModelAndView mv = new ModelAndView("/contract/custom-service-preview");
        mv.addObject("contract", contract);
        return mv;
    }

    //定制修改页
    @RequestMapping("/customServiceEdit")
    public ModelAndView customServiceEdit(Contract contract) {
        ModelAndView mv = new ModelAndView("/contract/custom-service-detail");
        mv.addObject("contract", contract);
        return mv;
    }

    //定制下载
    @RequestMapping("/customServiceDownload")
    public void customServiceDownload(Contract contract, HttpServletRequest request, HttpServletResponse response) throws IOException {
        FileTool.downloadCustomContract(contract, request, response);
    }

    //下载列表页
    @RequestMapping("/downloadServiceList")
    public ModelAndView downloadServiceList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "3") Integer pageSize) {
        ModelAndView mv = new ModelAndView("/contract/download-service-list");
        List<Contract> contracts = contractService.findDownloadContracts(pageNum, pageSize);
        PageInfo<Contract> page = new PageInfo<Contract>(contracts);
        mv.addObject("page", page);
        return mv;
    }

    //下载列表页查询
    @RequestMapping("/searchDownloadService")
    public ModelAndView searchDownloadService(ContractVo vo, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "3") Integer pageSize) {
        ModelAndView mv = new ModelAndView("/contract/download-service-list");
        List<Contract> contracts = contractService.findDownloadContractByVo(vo, pageNum, pageSize);
        PageInfo<Contract> page = new PageInfo<Contract>(contracts);
        mv.addObject("page", page);
        return mv;
    }

    //下载预览页
    @RequestMapping("/downloadServicePreview")
    public ModelAndView downloadServicePreview(Integer id, String name) throws Exception {
        ModelAndView mv = new ModelAndView("/contract/download-service-preview");
        Attachment attachment = attachmentService.findById(id);
        String text = FileTool.getDocxText(attachment.getPath());
        mv.addObject("text", text);
        mv.addObject("name", name);
        mv.addObject("id", id);
        return mv;
    }

//    //审核列表页查询 产品查询
//    @RequestMapping("/searchAuditService")
//    public ModelAndView searchAuditService(ProductVo vo, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "8") Integer pageSize) {
//        ModelAndView mv = new ModelAndView("/contract/audit-service-list");
//        List<Contract> contracts = contractService.findDownloadContractByVo(vo, pageNum, pageSize);
//        PageInfo<Contract> page = new PageInfo<Contract>(contracts);
//        mv.addObject("page", page);
//        return mv;
//    }

    //审核列表页
    @RequestMapping("/auditServiceList")
    public ModelAndView auditServiceList(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "3") Integer pageSize) {
        ModelAndView mv = new ModelAndView("/contract/audit-service-list");
        List<Product> products = productService.findContract(pageNum, pageSize);
        PageInfo<Product> page = new PageInfo<Product>(products);
        mv.addObject("page", page);
        return mv;
    }

    //审核购买页
    @RequestMapping("/auditServiceBuy")
    public ModelAndView auditServiceList(Product product) {
        ModelAndView mv = new ModelAndView("/contract/audit-service-buy");
        mv.addObject("product", product);
        return mv;
    }

    //生成审核订单
    @RequestMapping(value = "/addAuditOrder", method = RequestMethod.POST)
    public ModelAndView addAuditOrder(@RequestParam(name = "uploadFile") MultipartFile uploadFile, Integer productId, HttpServletRequest request) throws IOException {
        //跳转支付页
        ModelAndView mv = new ModelAndView("redirect:/contract/auditServiceList");

        //上传
        User user =(User) request.getSession().getAttribute("user");
        Integer userId = 0;
        if (user != null) {
            userId = user.getId();
        }
        Map<String, String> map = FileTool.fileUpload(uploadFile, request);
        if (map != null) {
            //生成附件表
            Attachment attachment = new Attachment(map.get("name"), map.get("path"), null, userId, userId);
            attachmentService.addAttachment(attachment);

            //判断页数字数 价格
            int pages = FileTool.getDocxPages(map.get("path"));
            int n = pages / 3 + 1;
            Product product = productService.findId(productId);
            Integer price = Integer.parseInt(product.getPrice()) * n;

            //生成订单表\产品实例

            Order order = new Order();
            order.setUserId(userId);//设置用户id
            order.setOrderNum("123456");
            order.setOrderName("合同审核");
            order.setServiceType("法律文书");
            order.setAllAmount(price.toString());
//          order.setSendOrderStatus("");
            order.setStatus("平台方未审核");//订单审核状态
            order.setAcceptStatus("未受理");//是否受理
            order.setCreateTime(new Date());
            order.setUpdateTime(new Date());
            order.setSendOrderStatus("未发布订单");//订单未发布
            order.setCreateBy(1);
            order.setUpdateBy(1);
            order.setFlowStatus("等待合同审核");
            order.setPayNum("654321");
            order.setPayStatus("已支付");
            order.setNextStatus("审核结果");
            orderService.addOrder(order, productId.toString());


            //生成审核记录表
            ContractAudit contractAudit = new ContractAudit();
            contractAudit.setCreateBy(userId);
            contractAudit.setUpdateBy(userId);
            contractAudit.setAttId(attachment.getId());
            contractAudit.setPageSize(pages);
            contractAudit.setOrderId(order.getId());//关联订单
            contractService.insertContractAudit(contractAudit);
        }


        return mv;
    }


}
